package ligacoes;
import dados.Stock;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import cliente.Cliente;

public class LigacaoAllStocks extends Thread {

	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private Cliente cliente;

	public LigacaoAllStocks(Cliente cliente, Socket socket) throws IOException{
		this.cliente = cliente;
		this.socket = socket;
		InputStream is = socket.getInputStream();
		in = new ObjectInputStream(is);
		OutputStream os = socket.getOutputStream();
		out = new ObjectOutputStream(os);
	}
	
	@SuppressWarnings("unchecked")
	public void run() {
		setName("Thread LigacaoActualizacao - Cliente");
		try {
			while (true) {
				Object obj = in.readObject();
				Date date = new Date();
				System.out.println("Data Actualizacao Cliente: " + date.toString());
				if(obj instanceof ArrayList<?>){
					ArrayList<Stock> stocks = (ArrayList<Stock>) obj;
					cliente.actualizarTabelaStocks(stocks);
					out.writeObject("Actualizado com sucesso");
				}else{
					out.writeObject("Actualizado sem sucesso");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Cliente(LigacaoAllStocks) - Terminado...");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			System.out.println("Cliente(LigacaoAllStocks) - a fechar...");
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}